$(function () {

    // app change
    $('#app').on('change', function () {
        //reload
        var app = $('#app').val();
        window.location.href = base_url + "/conf?app=" + app;
    });

    if (!hasPermission) {
        layer.open({
            icon: '2',
            content: '您没有该项目的配置权限,请联系管理员开通'
        });
        return;
    }

    // init date tables
    var confTable = $("#conf_list").dataTable({
        "deferRender": true,
        "processing": true,
        "serverSide": true,
        "ajax": {
            url: base_url + "/conf/pageList",
            type: "post",
            data: function (d) {
                var obj = {};
                obj.app = $('#app').val();
                obj.key = $('#key').val();
                obj.start = d.start;
                obj.length = d.length;
                return obj;
            }
        },
        "searching": false,
        "ordering": false,
        //"scrollX": true,	// X轴滚动条，取消自适应
        "columns": [
            {"data": 'id', 'width': '5%', "visible": true},
            {"data": 'env', 'width': '5%', "visible": true},
            {"data": 'app', 'width': '10%', "visible": true},
            {"data": 'key', 'width': '20%', "visible": true},
            {
                "data": 'value',
                'width': '15%',
                "visible": true,
                "render": function (data, type, row) {
                    var temp = (row.value.length > 20) ? row.value.substring(0, 20) + '...' : row.value;
                    return "<span title='" + row.value + "'>" + temp + "</span>";
                }
            },
            {
                "data": 'title',
                'width': '15%',
                "visible": true,
                "render": function (data, type, row) {
                    var temp = (row.title.length > 20) ? row.title.substring(0, 20) + '...' : row.title;
                    return "<span title='" + row.title + "'>" + temp + "</span>";
                }
            },
            {
                "data": 'type',
                'width': '5%',
                "visible": true,
                "render": function (data, type, row) {
                    var temp = "";
                    switch (row.type){
                        case 0: {
                            temp = "无效";
                            break;
                        }
                        case 1: {
                            temp = "全量生效";
                            break;
                        }
                        case 2: {
                            temp = "指定ip";
                            break;
                        }
                        case 3: {
                            temp = "指定集群";
                            break;
                        }
                    }
                    return "<span title='" + row.type + "'>" + temp + "</span>";
                }
            },
            {
                "data": 'serverInfos',
                'width': '15%',
                "visible": true,
                "render": function (data, type, row) {
                    var temp = (row.serverInfos.length > 20) ? row.serverInfos.substring(0, 20) + '...' : row.serverInfos;
                    return "<span title='" + row.serverInfos + "'>" + temp + "</span>";
                }
            },
            {
                "data": '操作',
                'width': '10%',
                "render": function (data, type, row) {
                    return function () {
                        confData[row.id] = row;
                        var html = '<p key="' + row.id + '" >' +
                            '<button class="btn btn-warning btn-xs update" type="button">编辑</button>  ' +
                            '<button class="btn btn-danger btn-xs delete" type="button">删除</button>  ' +
                            '</p>';

                        return html;
                    };
                }
            }
        ],
        "language": {
            "sProcessing": "处理中...",
            "sLengthMenu": "每页 _MENU_ 条记录",
            "sZeroRecords": "没有匹配结果",
            "sInfo": "第 _PAGE_ 页 ( 总共 _PAGES_ 页 )",
            "sInfoEmpty": "无记录",
            "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
            "sInfoPostFix": "",
            "sSearch": "搜索:",
            "sUrl": "",
            "sEmptyTable": "表中数据为空",
            "sLoadingRecords": "载入中...",
            "sInfoThousands": ",",
            "oPaginate": {
                "sFirst": "首页",
                "sPrevious": "上页",
                "sNext": "下页",
                "sLast": "末页"
            },
            "oAria": {
                "sSortAscending": ": 以升序排列此列",
                "sSortDescending": ": 以降序排列此列"
            }
        }
    });

    $("#searchBtn").click(function () {
        confTable.fnDraw();
    });

    // tecTips
    var tecCache = {};
    $("#conf_list").on('click', '.tecTips', function () {
        var cacheKey = $(this).attr("cacheKey");
        var cacheValue = tecCache[cacheKey];
        ComAlertTec.show(cacheValue);
    });


    var confData = {};
    // 删除
    $("#conf_list").on('click', '.delete', function () {
        var key = $(this).parent('p').attr("key");
        layer.confirm("确定要删除id为：" + key + "的配置吗", {
            icon: 3,
            title: '系统提示',
            btn: ['确定', '取消']
        }, function (index) {
            layer.close(index);
            $.post(
                base_url + "/conf/delete?id=" + key,
                function (data, status) {
                    if (data.code === 200) {
                        layer.open({
                            icon: '1',
                            content: '删除成功',
                            end: function (layero, index) {
                                confTable.fnDraw();
                            }
                        });
                    } else {
                        layer.open({
                            icon: '2',
                            content: (data.msg || '删除失败')
                        });
                    }
                }
            );

        });

    });

    // jquery.validate 自定义校验
    jQuery.validator.addMethod("myValid01", function (value, element) {
        var length = value.length;
        var valid = /^[a-z][a-z0-9.]*$/;
        return this.optional(element) || valid.test(value);
    }, "限制以小写字母开头，由小写字母、数字和.组成");

    // 新增
    $("#add").click(function () {
        $('#addModal').modal('show');
    });
    var addModalValidate = $("#addModal .form").validate({
        errorElement: 'span',
        errorClass: 'help-block',
        focusInvalid: true,
        rules: {
            key: {
                required: true,
                rangelength: [0, 200],
                myValid01: true
            },
            value: {
                required: true
            }
        },
        messages: {
            key: {
                required: '请输入配置Key',
                rangelength: "配置Key长度限制为0~200"
            },
            value: {
                required: '请输入配置'
            }
        },
        highlight: function (element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement: function (error, element) {
            element.parent('div').append(error);
        },
        submitHandler: function (form) {
            $.post(base_url + "/conf/add",$("#addModal .form").serialize(), function (data, status) {
                if (data.code === 200) {
                    layer.open({
                        icon: '1',
                        content: '新增成功',
                        end: function (layero, index) {
                            confTable.fnDraw();
                            $('#addModal').modal('hide');
                        }
                    });
                } else {
                    layer.open({
                        icon: '2',
                        content: (data.msg || '新增失败')
                    });
                }
            });
        }
    });
    $("#addModal").on('hide.bs.modal', function () {
        $("#addModal .form")[0].reset()
        addModalValidate.resetForm();
        $("#addModal .form .form-group").removeClass("has-error");
    });

    // 更新
    $("#conf_list").on('click', '.update', function () {

        var key = $(this).parent('p').attr("key");
        var row = confData[key];

        $("#updateModal .form input[name='id']").val(row.id);
        $("#updateModal .form input[name='env']").val(row.env);
        $("#updateModal .form select[name='app']").find("option[value='"+ row.app +"']").prop("selected", 'selected');
        $("#updateModal .form input[name='key']").val(row.key);
        $("#updateModal .form input[name='app']").val(row.app);
        $("#updateModal .form input[name='title']").val(row.title);
        $("#updateModal .form textarea[name='value']").val(row.value);
        $("#updateModal .form select[name='type']").find("option[value='"+ row.type +"']").prop("selected", 'selected');
        $("#updateModal .form input[name='serverInfos']").val(row.serverInfos);

        $('#updateModal').modal('show');
    });
    var updateModalValidate = $("#updateModal .form").validate({
        errorElement: 'span',
        errorClass: 'help-block',
        focusInvalid: true,
        rules: {
            key: {
                required: true,
                rangelength: [0, 200],
                myValid01: true
            },
            value: {
                required: true
            }
        },
        messages: {
            key: {
                required: '请输入配置Key',
                rangelength: "配置Key长度限制为0~200"
            },
            value: {
                required: '请输入配置'
            }
        },
        highlight: function (element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        success: function (label) {
            label.closest('.form-group').removeClass('has-error');
            label.remove();
        },
        errorPlacement: function (error, element) {
            element.parent('div').append(error);
        },
        submitHandler: function (form) {
            $.post(
                base_url + "/conf/update",
                $("#updateModal .form").serialize(),
                function (data, status) {
                if (data.code === 200) {
                    layer.open({
                        icon: '1',
                        content: '更新成功',
                        end: function (layero, index) {
                            confTable.fnDraw();
                            $('#updateModal').modal('hide');
                        }
                    });
                } else {
                    layer.open({
                        icon: '2',
                        content: (data.msg || '更新失败')
                    });
                }
            });
        }
    });
    $("#updateModal").on('hide.bs.modal', function () {
        $("#updateModal .form")[0].reset()
        updateModalValidate.resetForm();
        $("#updateModal .form .form-group").removeClass("has-error");
    });

});
